import 'dart:io';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/pages/love_record/published_ui/open_image.dart';
import 'package:love_app/providers/image_list_model.dart';
import 'package:love_app/providers/love_record_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/service/add_recore_api.dart';
import 'package:photo/photo.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';

/// 发表动态页面
class AddPublished extends StatefulWidget {
  final String apiPath;
  final String appBarTitel;

  AddPublished({this.apiPath, this.appBarTitel});
  @override
  _AddPublishedState createState() => _AddPublishedState();
}

class _AddPublishedState extends State<AddPublished> {
  // 页面主要的字体颜色
  final Color _textColor = Color.fromRGBO(178, 178, 178, 1);
  BuildContext _context;
  int _maxSelected = 9;
  TextEditingController _contentController = TextEditingController(); // 用户名控制器
  ShareProvider _shareProvider; // 全局共享数据
  ImageListModel _imageListModel; // 局部变量共享
  LoveRecordProvider _loveRecordProvider; // 恋爱记录共享数据

  @override
  void initState(){
    // 监听文本框变化
    _contentController.addListener((){
      setState(() {});
    });
    super.initState();
  }

  // 只执行一次， 用来获取共享数据
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _imageListModel = Provider.of<ImageListModel>(context, listen: true);
    _loveRecordProvider =
        Provider.of<LoveRecordProvider>(context, listen: false);
  }

  @override
  void dispose() {
    _imageListModel.cleanItem(); // 清除数组
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _maxSelected = 10 - _warpChildren().length;
    _context = context;
    return Scaffold(
      appBar: Su().appBar(
        widget.appBarTitel,
        colors: _shareProvider.themeColor,
        actionText: '发布',
        onActionClick: _add,
      ),
      backgroundColor: Color.fromRGBO(243, 244, 246, 1),
      body: _body(),
    );
  }

  // 发布按钮的实现
  Future<void> _add()async{
    String token = _shareProvider.token;
    List filePathList = _imageListModel.getAllItem();
    String content = _contentController.text;
    String formToken = _shareProvider.formToken;
    String apiPath = AddRecordApi.getPostApi(widget.apiPath);
    if(filePathList.length > 0){
      // 如果有上上传文件的话，就先上传文件
      await AddRecordApi(apiPath: apiPath).create(token, filePathList, content, formToken);
    }else{
      await AddRecordApi(apiPath: apiPath).createOnlyText(token, content, formToken);
    }
    _loveRecordProvider.notify();
    _shareProvider.updateFormToken();
    Navigator.pop(context);
  }

  // 页面内容
  Widget _body() {
    return Container(
      color: Colors.white,
      height: _warpChildren().length > 5 ? Su().h(730) : Su().h(559),
      padding: EdgeInsets.only(
        left: Su().w(40),
        right: Su().w(40),
      ),
      child: Column(
        children: <Widget>[
          _inputFile(),
          _borderWarp(),
        ],
      ),
    );
  }

  // 网格布局
  Widget _borderWarp() {
    return Align(
      alignment: Alignment.centerLeft, // 价格Align让网格向左对齐
      child: Padding(
        padding: EdgeInsets.only(top: Su().h(20)),
        child: Wrap(
          spacing: Su().w(25),
          runSpacing: Su().w(20),
          children: _warpChildren(),
        ),
      ),
    );
  }

  // warp布局的内容
  List<Widget> _warpChildren(){
    List listItem =  _imageListModel.getAllItem();
    List<Widget> widgets = [];
    widgets.add(_warpFirstWidget());
    for (String item in listItem){
      File file = File(item);
      widgets.add(_everyImage(file));
    }
    return widgets;
  }

  // 网格布局第一个widget
  Widget _warpFirstWidget() {
    return DottedBorder(
      color: _textColor,
      strokeWidth: 2,
      child: Container(
        width: Su().w(100),
        height: Su().w(100),
        child: addImage(),
      ),
    );
  }

  // 一个按钮，点击可打开图库
  Widget addImage() {
    return IconButton(
      padding: EdgeInsets.all(0),
      icon: Icon(
        Icons.add,
        color: _textColor,
      ),
      onPressed: () async {
        List<AssetEntity> imgList = await _pickAsset();
        for (var e in imgList) {
          var file = await e.file;
          // _everyImage(file);
          _imageListModel.addItem(file: file);
        }
        _imageListModel.notiy();
      },
    );
  }

  // 每个图片的内容
  _everyImage(File file) {
    return InkWell(
      child: Container(
        width: Su().w(110),
        height: Su().w(110),
        child: Image.file(
          file,
          fit: BoxFit.fitWidth,
        ),
      ),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(
            builder: (context){
              return HeroAnimationRouteB(file: file);
            }
          ));
        
      },
    );
  }

  // 文本输入框
  Widget _inputFile() {
    return TextField(
      autofocus: false,
      decoration: _inputDecoration(),
      maxLines: 8,
      maxLength: 1024,
      controller: _contentController,
    );
  }

  // 文本输入框样式
  InputDecoration _inputDecoration() {
    return InputDecoration(
      hintText: '在这里记录我们的点点滴滴...',
      hintStyle: Su().textStyle(_textColor, 28),
      // 未获得焦点下划线
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.white),
      ),
      //获得焦点下划线设
      focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: _shareProvider.textColor),
      ),
    );
  }

  Future<List<AssetEntity>> _pickAsset() async {
    // var assetPathList = await PhotoManager.getImageAsset();
    // Su.suPrints(assetPathList);

    List<AssetEntity> imgList = await PhotoPicker.pickAsset(
      context: _context,
      themeColor: _shareProvider.textColor,
      padding: 1.0,
      dividerColor: Colors.white,
      disableColor: Colors.grey.shade300,
      itemRadio: 0.88,
      maxSelected: _maxSelected,
      provider: I18nProvider.chinese,
      rowCount: 5,
      textColor: Colors.white,
      thumbSize: 150,
      sortDelegate: SortDelegate.common,
      checkBoxBuilderDelegate: DefaultCheckBoxBuilderDelegate(
        activeColor: Colors.white,
        unselectedColor: Colors.white,
        checkColor: Colors.blue,
      ),
      pickType: PickType.onlyImage,
    );
    return imgList;
  }
}